import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier


def calculate_accuracy(random_seed):
    # 加载 iris 数据集
    iris = load_iris()
    features, labels = iris.data, iris.target
    # 将数据集划分为训练集 (80%) 和测试集 (20%)
    features_train, features_test, labels_train, labels_test = \
        train_test_split(features, labels, test_size=0.2, random_state=random_seed)
    # 创建 KNN 分类器, 设置近邻数为 5
    knn_classifier = KNeighborsClassifier(n_neighbors=5)
    # 通过训练集训练模型
    knn_classifier.fit(features_train, labels_train)
    # 对测试集进行预测
    labels_test_predict = knn_classifier.predict(features_test)
    # 基于测试集预测结果对预测模型的准确率进行评估
    accuracy = accuracy_score(labels_test, labels_test_predict)
    return accuracy


seed_values = range(1, 201)  # 不同的随机种子值范围
accuracies = [calculate_accuracy(seed) for seed in seed_values]
# 绘图
plt.figure(figsize=(10, 6))
plt.plot(seed_values, accuracies, marker='o', linestyle='-')
plt.title('The Accuracy of different Random Seed')
plt.xlabel('Random Seed')
plt.ylabel('Accuracy')
plt.grid(True)
plt.show()
